﻿using Model;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Business
{
    public class UserBiz
    {
        public int SaveItem(User item)
        {
            var dbContext = new Context();

            dbContext.Users.Add(item);
            dbContext.SaveChanges();

            return item.Id;
        }

        public void UpdateItem(User item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public User LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.Users
                    where item.Id == id
                    select item).First();
        }

        public void RemoveItem(List<User> items)
        {
            var dbContext = new Context();
            foreach (var item in items)
            {
                dbContext.Users.Attach(item);
                dbContext.Users.Remove(item);
                dbContext.Entry(item).State = EntityState.Deleted;
            }

            dbContext.SaveChanges();
        }

        public List<User> LoadItems()
        {
            var dbContext = new Context();
            return (from item in dbContext.Users
                    select item).OrderBy(item => item.Username).ToList();
        }

        public List<User> LoadDelivery()
        {
            var dbContext = new Context();
            return (from item in dbContext.Users
                    where item.Type == "Vận chuyển"
                    select item).OrderBy(item => item.Username).ToList();
        }

        public User Login(string account, string password)
        {
            var encodedPassword = Utility.EncodePassword(password);

            var dbContext = new Context();
            var users = (from item in dbContext.Users
                         where (item.Username == account && item.Password == encodedPassword)
                         select item);

            if (!users.Any())
            {
                return null;
            }
            return users.First();
        }

        public bool IsAccountExist(string account)
        {            
            var dbContext = new Context();
            var user = (from item in dbContext.Users
                    where item.Username.ToLower() == account.ToLower()
                    select item).ToList();

            if (user != null && user.Count > 0)
                return true;

            return false;
        }
    }
}
